package com.wechat.scheme.aspect;

import com.wechat.scheme.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;


@Aspect
@Component
@Slf4j
public class ControllerValidAspect {

    @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
    public void Pointcut() {
    }

    @Around("Pointcut()")
    public Object Around(ProceedingJoinPoint pjp) throws Throwable {
        log.info("Class:" + pjp.getTarget().getClass().getName()+ "/Method:"+pjp.getSignature().getName());
        Object[] args = pjp.getArgs();
        if (args != null && args.length > 0) {
            for (Object obj : args) {
                if (obj instanceof BindingResult) {
                    BindingResult bindResult = (BindingResult) obj;
                    if (bindResult.hasErrors()) {
                        for (ObjectError error : bindResult.getAllErrors()) {
                            return Response.fail(error.getDefaultMessage());
                        }
                    }
                }
            }
        }
        return pjp.proceed();
    }
}
